//
//  GoEasyMessageEncoder.swift
//  uwantgoeasy
//
//  Created by 冯传宝 on 12/11/15.
//  Copyright © 2015 uwantsoft. All rights reserved.
//

import Foundation

class GoEasyMessageEncoder {

    func encode(clientMessage: ClientMessage) ->[UInt8]{
        let typeCode = clientMessage.typeCode()
        let subTypeBytes:[UInt8] = toByteArray(typeCode)
        let contentStr:String = clientMessage.jsonAsString()
        let contentData = contentStr.dataUsingEncoding(NSUTF8StringEncoding)
        let contentBase64Encoded:String=contentData!.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
        let contentBytes:[UInt8] = Array(contentBase64Encoded.utf8)
        return subTypeBytes+contentBytes
    }
    
    func toByteArray(value: Int) -> [UInt8] {
        var msgLength = [UInt8](count: 4, repeatedValue: 0)
        
        for i in 0...3 {
            msgLength[i] = UInt8(0x0000FF & value >> Int((3 - i) * 8))
        }
        return msgLength
    }
}